package com.XDApp.xdbase.activitys;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.XDApp.xdbase.BaseActivity;
import com.XDApp.xdbase.BaseApplication;
import com.XDApp.xdbase.XDHttpClient;
import com.XDApp.xdbase.alipay.Keys;
import com.XDApp.xdbase.alipay.Result;
import com.XDApp.xdbase.alipay.Rsa;
import com.XDApp.xdbase.utils.CommonUtil;
import com.XDApp.xdbase.utils.ProgressHUD;
import com.XDApp.xdbase.utils.xdConfig;
import com.XDApp.xdbase.xinsilu.R;
import com.alipay.android.app.sdk.AliPay;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/** 订单详情*/
public class OrderDetailActivity extends BaseActivity implements OnClickListener {

	private static final String TAG = "订单详情";

	private int payKind = 1;// 支付方式 0:网页版支付 1:客户端支付

	/** 未支付*/
	public final static int UNPAID = 0;
	/** 已支付*/
	public final static int PAID = 1;

	private int payType = 0;
	/** 0门票1特产*/
	private int type = 0;

	private LinearLayout ll_addr;
	private LinearLayout ll_unoadi;
	private RelativeLayout rl_bottom;
	private RelativeLayout rl_playtime;
	/** 订单标题*/
	private TextView tvTitle;
	/** 订单编号*/
	private TextView tvOrderCode;
	/** 下单时间*/
	private TextView tvOrderTime;
	/** 是否支付*/
	private TextView tvOrderType;
	/** 订单来源*/
	private TextView tvOrderName;
	/** 总额*/
	private TextView tvPrice;
	/** 游玩时间*/
	private TextView tvPlayTime;
	/** 联系人姓名*/
	private TextView tvContactName;
	/** 联系人电话*/
	private TextView tvContactNum;
	/** 地址*/
	private TextView tvAddr;
	/** 去支付*/
	private Button btnPay;
	/** 取消订单*/
	private Button btnCancle;
	/** 支付方式*/
	private RadioGroup rg;
	private RadioButton rb01;
	private RadioButton rb02;

	/** 订单编号*/
	private String orderId = "";
	/**　游玩时间*/
	private String orderPlayTime = "";
	/**　下单时间*/
	private String orderTime = "";
	/**　订单门票的用户名*/
	private String orderUserName = "";
	/**　订单门票的电话*/
	private String orderPhone = "";
	// /**　订单门票的地址*/
	// private final String orderAdress = "这个是假地址";
	/**　门票id*/
	private final String mpId = "";
	/**　用户id*/
	private String userId = "";
	/**　取消原因*/
	private String reason = "";
	/**　订单的标题*/
	private String orderName = "";
	/**　总额*/
	private String totalPrice;
	/**　地址*/
	private String orderAdress;
	/**　数量*/
	private String num;
	/**  应付价钱*/
	private TextView tv_pay;
	private BaseApplication mApplication;

	/**   标题控件*/
	private ImageView back;
	private TextView title;

	private static final int RQF_PAY = 1;
	private static final int RQF_LOGIN = 2;

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			Result result = new Result((String) msg.obj);

			switch (msg.what) {
			case RQF_PAY:
				Toast.makeText(OrderDetailActivity.this, result.getResult(), Toast.LENGTH_SHORT).show();
				if (CommonUtil.checkNetState(mContext)) {
					RequestParams params = new RequestParams();
					params.put("orderSn", orderId);
					params.put("userID", userId);
					params.put("ostype", "ANDROID");

					final ProgressHUD ProgressDialog = ProgressHUD
							.show(mContext, "正在加载...", true, true, null);
					XDHttpClient.post(xdConfig.SEND_ORDER, params, new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int statusCode, String content) {
							if (null != ProgressDialog && ProgressDialog.isShowing())
								ProgressDialog.dismiss();
							Log.i(TAG, content);
							JSONObject obj;
							try {
								obj = new JSONObject(content);
								String state = obj.getString("state");
								String msg = obj.getString("msg");

								// 判断返回数据是否正确
								if (state.equals("1")) {
									ll_unoadi.setVisibility(View.GONE);
									rl_bottom.setVisibility(View.GONE);
									tvOrderType.setText("已支付");
								} else {
									CommonUtil.showToast(mContext, msg);
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}

						@Override
						public void onFailure(Throwable arg0, String arg1) {
							if (null != ProgressDialog && ProgressDialog.isShowing()) {
								ProgressDialog.dismiss();
							}
							super.onFailure(arg0, arg1);
							Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
						}
					});
				} else {
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
				}
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void initViews() {
		setContentView(R.layout.activity_orderdetail);

		mApplication = BaseApplication.getApplication();

		ll_addr = (LinearLayout) findViewById(R.id.ll_address);
		ll_unoadi = (LinearLayout) findViewById(R.id.ll_no_pay);
		rl_bottom = (RelativeLayout) findViewById(R.id.rl_bottom);
		rl_playtime = (RelativeLayout) findViewById(R.id.rl_playtime);

		tvOrderCode = (TextView) findViewById(R.id.tv_order_code);
		tvOrderTime = (TextView) findViewById(R.id.tv_order_time);
		tvOrderName = (TextView) findViewById(R.id.tv_order_name);
		tvPrice = (TextView) findViewById(R.id.tv_price);
		tvPlayTime = (TextView) findViewById(R.id.tv_paly_time);
		tvContactName = (TextView) findViewById(R.id.tv_contact_name);
		tvContactNum = (TextView) findViewById(R.id.tv_contact_num);
		tvAddr = (TextView) findViewById(R.id.tv_addr);
		tvOrderType = (TextView) findViewById(R.id.tv_order_type);
		tvTitle = (TextView) findViewById(R.id.tvTitle);

		btnPay = (Button) findViewById(R.id.btn_pay);
		btnCancle = (Button) findViewById(R.id.btn_cancle_order);
		rg = (RadioGroup) findViewById(R.id.radiogroup);
		rb01 = (RadioButton) findViewById(R.id.rb_01);
		rb02 = (RadioButton) findViewById(R.id.rb_02);

		btnPay.setOnClickListener(this);
		btnCancle.setOnClickListener(this);
		// 标题控件
		back = (ImageView) findViewById(R.id.title_back);
		back.setOnClickListener(this);
		title = (TextView) findViewById(R.id.title_text);
		title.setText("订单详情");

		tv_pay = (TextView) findViewById(R.id.tv_pay);
	}

	@Override
	protected void initEvents() {

		userId = mApplication.getUser().getUserID();

		orderId = getIntent().getStringExtra("orderId");
		// payType = getIntent().getIntExtra("payType", 0);
		type = getIntent().getIntExtra("type", 1);
		// totalPrice = getIntent().getStringExtra("totalPrice");
		// orderUserName = getIntent().getStringExtra("orderUserName");
		// orderPhone = getIntent().getStringExtra("orderPhone");
		// orderId = getIntent().getStringExtra("orderId");
		// orderTime = getIntent().getStringExtra("orderTime");
		// orderPlayTime = getIntent().getStringExtra("orderPlayTime");
		// orderName = getIntent().getStringExtra("orderName");
		// orderAdress = getIntent().getStringExtra("orderAdress");

		getDetail();

		rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId == rb01.getId()) {
					showShortToast("选择了０１");
					payKind = 0;
				} else if (checkedId == rb02.getId()) {
					showShortToast("选择了02");
					payKind = 1;
				}
			}
		});

	}

	private void setDetail() {
		if (type == 1) {
			ll_addr.setVisibility(View.VISIBLE);
			tvAddr.setText(orderAdress);
			tvTitle.setText("特产信息");
			rl_playtime.setVisibility(View.GONE);

		} else if (type == 0) {
			tvPlayTime.setText(orderPlayTime);
			ll_addr.setVisibility(View.GONE);
		}

		tvOrderCode.setText(orderId);
		tvOrderTime.setText(orderTime);
		tvOrderName.setText(orderName);
		tvPrice.setText(totalPrice + "元");
		tv_pay.setText(totalPrice + "元");
		tvContactName.setText(orderUserName);
		tvContactNum.setText(orderPhone);

		if (payType == 0) {
			ll_unoadi.setVisibility(View.VISIBLE);
			rl_bottom.setVisibility(View.VISIBLE);
			tvOrderType.setText("未支付");
		} else {
			ll_unoadi.setVisibility(View.GONE);
			rl_bottom.setVisibility(View.GONE);
			tvOrderType.setText("已支付");
		}
	};

	@Override
	public void onClick(View v) {
		// Intent intent ;
		switch (v.getId()) {
		case R.id.btn_pay:
			showShortToast("去支付");
			if (payKind == 0) {// 网页版支付
//				getWebData();
			} else {// 客户端支付
				// TODO
				String info = getNewOrderInfo();
				String sign = Rsa.sign(info, Keys.PRIVATE);
				sign = URLEncoder.encode(sign);
				info += "&sign=\"" + sign + "\"&" + getSignType();
				Log.i("ExternalPartner", "start pay");
				// start the pay.
				Log.i(TAG, "info = " + info);

				final String orderInfo = info;
				new Thread() {
					@Override
					public void run() {
						AliPay alipay = new AliPay(OrderDetailActivity.this, mHandler);

						// 设置为沙箱模式，不设置默认为线上环境
						// alipay.setSandBox(true);

						String result = alipay.pay(orderInfo);

						if (!TextUtils.isEmpty(result)) {
							Log.i(TAG, "result = " + result);
							Message msg = new Message();
							msg.what = RQF_PAY;
							msg.obj = result;
							mHandler.sendMessage(msg);
						}
					}
				}.start();
			}
			break;
		case R.id.btn_cancle_order:
			// showShortToast("取消订单");
			final String[] items = new String[] { "不想买了", "信息填写错误，重新预订", "其他原因" };
			new AlertDialog.Builder(OrderDetailActivity.this).setTitle("取消原因")
					.setItems(items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case 0:
								reason = items[0];
								break;
							case 1:
								reason = items[1];
								break;
							case 2:
								reason = items[2];
								break;
							}
							cancleOrder();
						}
					}).show();

			break;
		case R.id.title_back:
			finish();
			break;
		default:
			break;
		}

	}

	private String getNewOrderInfo() {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&out_trade_no=\"");
		sb.append(getOutTradeNo());
		sb.append("\"&subject=\"");// 订单标题
		sb.append(orderName);
		sb.append("\"&body=\"");// 订单内容
		sb.append(orderName);
		sb.append("\"&total_fee=\"");// 订单价格
		sb.append(0.01);
		sb.append("\"&notify_url=\"");

		// 网址需要做URL编码
		sb.append(URLEncoder.encode("http://notify.java.jpxx.org/index.jsp"));
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}

	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
		Date date = new Date();
		String key = format.format(date);

		java.util.Random r = new java.util.Random();
		key += r.nextInt();
		key = key.substring(0, 15);
		Log.d(TAG, "outTradeNo: " + key);
		return key;
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	/**
	 * 获取订单详情
	 */
	private void getDetail() {
		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();
			params.put("orderId", orderId);
			params.put("userID", userId);
			params.put("ostype", "ANDROID");

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(xdConfig.GET_GETORDERDETAIL, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();
					Log.i(TAG, content);
					JSONObject obj;
					try {
						obj = new JSONObject(content);
						String state = obj.getString("state");
						String msg = obj.getString("msg");

						// 判断返回数据是否正确
						if (state.equals("1")) {
							JSONObject objDate = obj.getJSONObject("data");

							String str = objDate.getString("orderType");
							if (null != str && str.equals("1")) {
								payType = 1;
							} else {
								payType = 0;
							}
							orderTime = objDate.getString("orderTime");
							orderName = objDate.getString("orderName");
							totalPrice = objDate.getString("orderPrice");
							orderPlayTime = objDate.getString("orderPlayTime");
							orderUserName = objDate.getString("orderUserName");
							orderPhone = objDate.getString("orderPhone");
							orderAdress = objDate.getString("adress");
							num = objDate.getString("num");

							setDetail();

							// 关闭掉这个Activity
						} else {
							CommonUtil.showToast(mContext, msg);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();

				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}

	}

	/**
	 * 取消订单
	 */
	private void cancleOrder() {

		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();
			params.put("orderId", orderId);
			params.put("userID", userId);
			params.put("reason", reason);
			params.put("ostype", "ANDROID");

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(xdConfig.GET_CANORDER, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {
					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();
					JSONObject obj;
					try {
						obj = new JSONObject(content);
						String state = obj.getString("state");
						String msg = obj.getString("msg");

						// 判断返回数据是否正确
						if (state.equals("1")) {
							CommonUtil.showToast(mContext, "取消成功！");
							finish();
							// 关闭掉这个Activity
						} else {
							CommonUtil.showToast(mContext, msg);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();

				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}

	/**
	 * 支付宝网页支付
	 */
	/*private void getWebData() {

		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();
			params.put("WIDout_trade_no", orderId);
			params.put("WIDsubject", "苹果耳机");
			params.put("WIDtotal_fee", "100");
			params.put("WIDis_buy", "2");
			params.put("uuid", "1000000000");
			// WIDout_trade_no=%@&WIDsubject=%@&WIDtotal_fee=%.2f&WIDis_buy=%@&uuid=%@
			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post("http://121.101.223.103:443/pay/alipayapi.jsp", params,
					new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int statusCode, String content) {
							if (null != ProgressDialog && ProgressDialog.isShowing())
								ProgressDialog.dismiss();
							JSONObject obj;
							try {
								obj = new JSONObject(content);
								String state = obj.getString("state");
								String msg = obj.getString("msg");

								// 判断返回数据是否正确
								if (state.equals("1")) {
									Intent intent = new Intent(OrderDetailActivity.this, PayWebActivity.class);
									startActivity(intent);
									finish();
									// 关闭掉这个Activity
								} else {
									CommonUtil.showToast(mContext, msg);
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}

						@Override
						public void onFailure(Throwable arg0, String arg1) {
							if (null != ProgressDialog && ProgressDialog.isShowing()) {
								ProgressDialog.dismiss();
							}
							super.onFailure(arg0, arg1);
							Toast.makeText(mContext, R.string.pLease_check_network, 0).show();

						}
					});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}*/
}
